package so.sao.code.service.domain.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import so.sao.code.service.domain.entity.RangeActivation;
import so.sao.code.service.domain.entity.TagBatch;
import so.sao.code.service.infrastructure.enums.CodeMessage;
import so.sao.code.service.infrastructure.enums.TAG_BATCH_STATUS;
import so.sao.code.service.infrastructure.enums.TagBatchStatus;
import so.sao.code.service.repository.RangeActivationDao;
import so.sao.code.service.repository.TagBatchDao;
import so.sao.tag.encryptor.TagCodeDriver;
import so.sao.top.core.util.rest.RestException;

/**
 * Created by Administrator on 2017/9/13.
 */
@Service
public class TagBatchDomainService {
	@Autowired
	TagBatchDao tagBatchDao;
	@Autowired
	RangeActivationDao rangeActivationDao;

	/**
	 * 激活批次的状态
	 */
	public void setTagBatchActiveStatus(RangeActivation rangeActivation, TagBatch tagBatch) {
		tagBatch.setStatus(TAG_BATCH_STATUS.ACTIVATED);
		if (!rangeActivation.isAll() && isPortionActivate(rangeActivation, tagBatch)) {
			tagBatch.setStatus(TAG_BATCH_STATUS.PORTION_ACTIVATE);
		}
		tagBatchDao.save(tagBatch);
	}

	/**
	 * 判断批次的标签是否全部激活
	 */
	private boolean isPortionActivate(RangeActivation rangeActivation, TagBatch tagBatch) {
		List<RangeActivation> rangeActivations = rangeActivationDao.findByTagBatchIdAndStatus(tagBatch.getId(),
				TagBatchStatus.ACTIVATED.getValue());
		if (rangeActivations.stream().mapToLong(item -> item.getSeqnumEnd() - item.getSeqnumStart() + 1)
				.sum() < (tagBatch.getSeqnumEnd() - tagBatch.getSeqnumStart() + 1)) {
			return true;
		}
		return false;
	}

	/**
	 * 校验二维码序号及域名长度数值
	 *
	 * @param codeUrlLength
	 * @param maxSeqnum
	 * @param domain
	 * @param subDomain
	 */
	public void checkDomainLength(int codeUrlLength, long maxSeqnum, String domain, String subDomain) {
		// 检查印刷格式设置中域名，子域名和码长度设置是否合法
		int maxUrlLength = TagCodeDriver.maxDomainLength(codeUrlLength, maxSeqnum);
		// url最大长度-子域名-两个slash
		int maxDomainLength = maxUrlLength - subDomain.length() - 2;
		if (maxDomainLength < domain.length()) {
			throw new RestException(HttpStatus.BAD_REQUEST, CodeMessage.CodeDomainNotSuitTheLength, maxDomainLength);
		}
	}
}
